import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {
    this.initializeAdmin()
  }

  findAll() {
    return this.usersRepository.find();
  }

  findOne(id: number) {
    return this.usersRepository.findOne({ where: { id } });
  }

  findByUsername(username: string) {
    return this.usersRepository.findOne({ where: { username } });
  }

  async createUser(userData: Partial<User>): Promise<User> {
    const user = this.usersRepository.create({
      ...userData,
      roles: userData.roles || ['user'],
    });
    return this.usersRepository.save(user);
  }

  private async initializeAdmin() {
    const admin = await this.findByUsername('admin')
    if (!admin) {
      await this.createUser({
        username: 'admin',
        password: 'admin123',
        name: '管理员',
        roles: ['admin']
      })
      console.log('管理员账号已初始化')
    }
  }
}
